using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace SPUserPoll.Business.Components
{
    /// <summary>
    /// Eventhandler used by the Answer and Response list
    /// mainly to reset the result and answer cache
    /// </summary>
    public class AnswerAndResponseEventHandler : SPItemEventReceiver
    {
        const string c_CacheResultsKey = "SPUserPollResultsTable_{0}";
        const string c_CacheAnswerKey = "SPUserPollAnswerTable_{0}";
        const string c_AnswersListName = "SPUserPoll answers";

        public override void ItemAdded(SPItemEventProperties properties)
        {
            //Reset the cache
            ResetCache(properties.ListItem);
            base.ItemAdded(properties);
        }

        public override void ItemUpdated(SPItemEventProperties properties)
        {
            //Reset the cache
            ResetCache(properties.ListItem);
            base.ItemUpdated(properties);
        }

        public override void ItemDeleting(SPItemEventProperties properties)
        {
            //Reset the cache
            ResetCache(properties.ListItem);
            base.ItemDeleting(properties);
        }

        /// <summary>
        /// Reset the answer or response cache
        /// </summary>
        /// <param name="item"></param>
        private void ResetCache(SPListItem item)
        {
            //retrieve the folder name from the itemurl, because the folder property of the item is always empty :(
            string itemFolderName = GetFolderName(item.Url, 2);
            
            //reset the cache of both items
            //reset the cache for answer list
            Business.Components.ManageLists.ResetCache(item.Web, itemFolderName, Types.CacheList.Answers);
            //reset the cache for response list
            Business.Components.ManageLists.ResetCache(item.Web, itemFolderName, Types.CacheList.Responses);
        }

        /// <summary>
        /// Get the foldername of the given url
        /// </summary>
        /// <param name="itemUrl"></param>
        /// <param name="position"></param>
        /// <returns></returns>
        private string GetFolderName(string itemUrl, int position)
        {
            if (itemUrl != null)
            {
                string[] folders = itemUrl.Split("/".ToCharArray());
                if (folders.Length > 0)
                {
                    return (folders[folders.Length - position]);
                }
            }
            //return empty string
            return null;
        }

    }
}
